const express = require('express')
const router = express.Router()
const Project = require('../models/Project')
const { markFileAsReferenced, unmarkFileReference } = require('../middlewares/fileReference')
const authMiddleware = require('../middlewares/auth')
// 创建项目指导记录
router.post('/addProject', authMiddleware(), async (req, res) => {
  try {
    const { completionDate, fileId, projectName, industry, description, partners, isSuccessCase } = req.body

    // 验证日期格式
    if (!/^\d{4}-\d{2}-\d{2}$/.test(completionDate)) {
      return res.status(400).json({ message: '日期格式应为YYYY-MM-DD' })
    }

    const newProject = new Project({
      completionDate,
      files: fileId,
      projectName,
      industry,
      description,
      partners: partners || [],
      isSuccessCase: isSuccessCase || 0
    })

    const savedProject = await newProject.save()
    await markFileAsReferenced(fileId)

    res.status(201).json({
      data: savedProject,
      message: '创建成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 查询项目指导记录（支持多条件筛选）
router.get('/queryProjects', async (req, res) => {
  try {
    const { year, projectId, projectName, pageNum = 1, pageSize = 10 } = req.query
    const filter = {}
    const options = {
      skip: (pageNum - 1) * pageSize,
      limit: parseInt(pageSize),
      sort: { completionDate: -1 }
    }

    if (projectId) filter._id = projectId
    if (year) filter.year = parseInt(year)
    if (projectName) {
      // 模糊查询
      filter.projectName = { $regex: projectName, $options: 'i' }
    }
    const [projects, total] = await Promise.all([
      Project.find(filter).populate('files').skip(options.skip).limit(options.limit).sort(options.sort),
      Project.countDocuments(filter)
    ])

    res.json({
      data: projects,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / options.limit),
      total,
      message: '查询成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新项目指导记录
router.post('/updateProject', authMiddleware(), async (req, res) => {
  try {
    const { fileId, projectId, completionDate, projectName, description, partners, isSuccessCase } = req.body
    const project = await Project.findById(projectId)

    if (!project) return res.status(404).json({ message: '项目不存在' })

    // 处理文件更新
    if (fileId && fileId !== project.files.toString()) {
      await unmarkFileReference(project.files)
      await markFileAsReferenced(fileId)
      project.files = fileId
    }

    // 更新年份（如果修改了完成日期）
    if (completionDate) {
      project.year = new Date(completionDate).getUTCFullYear()
    }

    Object.assign(project, { completionDate, projectName, description, partners, isSuccessCase })
    const updatedProject = await project.save()

    res.json({
      data: updatedProject,
      message: '更新成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 删除项目指导记录
router.post('/deleteProject', authMiddleware(), async (req, res) => {
  try {
    const project = await Project.findByIdAndDelete(req.body.projectId)
    if (!project) return res.status(404).json({ message: '项目不存在' })

    await unmarkFileReference(project.files)

    res.json({ message: '删除成功' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router
